<template>
  <view class="container">
    <!-- 月份切换 -->
    <view class="month-switch">
      <button @tap="changeMonth(-1)">‹</button>
      <text>{{ currentYear }}年{{ currentMonth + 1 }}月</text>
      <button @tap="changeMonth(1)">›</button>
    </view>

    <!-- 星期标题 -->
    <view class="calendar-grid">
      <view class="calendar-weekday" v-for="day in weekDays" :key="day">{{ day }}</view>

      <!-- 日历内容 -->
      <view
        v-for="(day, i) in calendarDays"
        :key="day.date + '_' + i"
        class="calendar-day"
        :class="{ active: selectedDate === day.date, disabled: !day.available || day.date < currentDate }"
        @tap="onSelectDate(day)"
      >
        <text>{{ day.day }}</text>
        <text v-if="!day.available && day.day" class="desc">(休息)</text>
        <text v-else-if="day.full" class="desc red">(已满)</text>
        <text v-else-if="day.date < currentDate" class="desc red"></text>
      </view>
    </view>

    <!-- 时间段部分 -->
    <view class="time-section" v-if="selectedDate">
      <view class="time-title">可预约时间段：{{ selectedDate }}</view>
      <view class="time-grid">
        <view
          class="time-slot"
          v-for="(slot, i) in selectedTimeSlots"
          :key="slot.time + '_' + i"
          :class="{ full: slot.full, selected: selectedTimeSlot === slot }"
          @tap="slot.full ? null : onSelectTime(slot)"
        >
          {{ slot.time }}
          <text v-if="slot.full" class="status">(已满)</text>
        </view>
      </view>
    </view>

    <!-- 立即预约按钮 -->
    <button class="book-now-btn" @tap="onBookNow" :disabled="!selectedDate || !selectedTimeSlot">
      立即预约
    </button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentYear: new Date().getFullYear(),
      currentMonth: new Date().getMonth(), // 注意：0 表示一月
      selectedDate: '',
      selectedTimeSlot: null, // 存储选中的时间段
      calendarDays: [],
      weekDays: ['日', '一', '二', '三', '四', '五', '六'],
      timeSlotMap: {},
      selectedTimeSlots: [],
      currentDate: '', // 当前日期
    };
  },
  mounted() {
    this.initCalendar();
  },
  methods: {
    initCalendar() {
      const today = new Date();
      this.currentDate = today.toISOString().split('T')[0]; // 获取今天的日期，格式为 "yyyy-mm-dd"

      const firstDay = new Date(this.currentYear, this.currentMonth, 1);
      const daysInMonth = new Date(this.currentYear, this.currentMonth + 1, 0).getDate();
      const startWeekday = firstDay.getDay();

      const days = [];

      // 补空格
      for (let i = 0; i < startWeekday; i++) {
        days.push({ day: '', date: '', available: false });
      }

      for (let d = 1; d <= daysInMonth; d++) {
        const date = new Date(this.currentYear, this.currentMonth, d);
        const ymd = date.toISOString().split('T')[0];
        const isWeekend = date.getDay() === 0 || date.getDay() === 6;

        const available = !isWeekend;
        const full = date.toDateString() === today.toDateString(); // 模拟“今天”为已满

        days.push({
          date: ymd,
          day: d,
          available,
          full
        });

        if (available) {
          this.timeSlotMap[ymd] = [
            { time: '09:00 - 10:00', full: d % 3 === 0 },
            { time: '10:30 - 11:30', full: false },
            { time: '14:00 - 15:00', full: d % 2 === 0 },
            { time: '15:30 - 16:30', full: false }
          ];
        }
      }

      this.calendarDays = days;
      this.selectedDate = '';
      this.selectedTimeSlots = [];
    },
    changeMonth(offset) {
      let newMonth = this.currentMonth + offset;
      let newYear = this.currentYear;

      if (newMonth < 0) {
        newMonth = 11;
        newYear--;
      } else if (newMonth > 11) {
        newMonth = 0;
        newYear++;
      }

      this.currentMonth = newMonth;
      this.currentYear = newYear;

      this.initCalendar();
    },
    onSelectDate(day) {
      if (!day.available || !day.date || day.date < this.currentDate) return;
      this.selectedDate = day.date;
      this.selectedTimeSlots = this.timeSlotMap[day.date] || [];
      this.selectedTimeSlot = null; // 清除之前的选中时间段
    },
    onSelectTime(slot) {
      if (slot.full) return;
      this.selectedTimeSlot = slot; // 设置选中的时间段
    },
    onBookNow() {
      if (!this.selectedDate || !this.selectedTimeSlot) {
        uni.showToast({
          title: '请选择日期和时间段',
          icon: 'none'
        });
        return;
      }

      uni.showToast({
        title: `预约成功：${this.selectedDate} ${this.selectedTimeSlot.time}`,
        icon: 'success'
      });

      // 在这里处理预约逻辑（如发送请求到后端）
    }
  }
};
</script>

<style scoped>
.container {
  padding: 30rpx;
}

.month-switch {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  font-size: 30rpx;
  font-weight: bold;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 10rpx;
}

.calendar-weekday {
  text-align: center;
  font-weight: bold;
  font-size: 26rpx;
  color: #333;
}

.calendar-day {
  padding: 15rpx 0;
  text-align: center;
  border-radius: 16rpx;
  background-color: #f5f5f5;
  font-size: 24rpx;
  min-height: 100rpx;
}

.calendar-day.active {
  background-color: #2979ff;
  color: #fff;
}

.calendar-day.disabled {
  color: #ccc;
  background-color: #eee;
}

.desc {
  display: block;
  font-size: 20rpx;
  color: #888;
}

.red {
  color: red;
}

.time-section {
  margin-top: 40rpx;
}

.time-title {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.time-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.time-slot {
  padding: 20rpx;
  background-color: #f0f0f0;
  border-radius: 14rpx;
  text-align: center;
  font-size: 26rpx;
}

.time-slot.full {
  color: #ccc;
  background-color: #eee;
}

.status {
  display: block;
  font-size: 22rpx;
  color: red;
}

.time-slot.selected {
  background-color: #2979ff;
  color: white;
}

.book-now-btn {
  width: 100%;
  padding: 20rpx;
  background-color: #2979ff;
  color: #fff;
  font-size: 28rpx;
  border-radius: 10rpx;
  margin-top: 40rpx;
}
</style>
